#
# common.mk
#
# Copyright (C) 2018 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

ifndef ARCH
	ARCH := i686-elf
endif

# Directories
SRCDIR       := src
OBJDIR       := obj
DEPDIR       := dep
TOOLSDIR     := tools
TOOLSROOTDIR := root

PROJECT_ROOT := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
export PATH  := $(PROJECT_ROOT)/$(TOOLSDIR)/$(TOOLSROOTDIR)/bin:$(PATH)

# Compilers and tools

ASM  := nasm

ifneq ($(ARCH), host)
	CC   := $(ARCH)-gcc
	LINK := $(ARCH)-ld
	LDFLAGS += -eprocess_startup
else
	CC   := gcc
	LINK := gcc
endif

ifeq ($(DEBUG), yes)
    CFLAGS += -g -DDEBUG
else
    CFLAGS += -O3
endif

ifeq ($(LINK_WITH_LIBGCC), yes)
	LIBGCCDIR := $(shell PATH=$(PATH) $(CC) -print-file-name=)
	LDFLAGS   += -L "$(LIBGCCDIR)" -lgcc
endif

# Output files
OUTPUTS := $(OUTPUT_KERNEL) $(OUTPUT_PROGRAM) $(OUTPUT_DRIVER) $(OUTPUT_STATIC_LIB) $(OUTPUT_DYNAMIC_LIB) $(ADDITIONAL_OBJECTS)
DEPENDS := $(shell find $(DEPDIR) -type f -name \*.d)
OBJECTS := $(patsubst $(SRCDIR)/%.c, $(OBJDIR)/%.o, $(patsubst $(SRCDIR)/%.asm, $(OBJDIR)/%.o, $(SOURCES)))

.PHONY: all clean

all: $(OBJDIR) $(DEPDIR) $(OUTPUTS)

-include $(DEPENDS)

clean:
	rm -f $(OUTPUTS)
	find $(OBJDIR) -name \*.o -delete
	find $(DEPDIR) -name \*.d -delete

$(OBJDIR):
	mkdir -p $(OBJDIR)

$(DEPDIR):
	mkdir -p $(DEPDIR)

$(OBJDIR)/%.o: $(SRCDIR)/%.c Makefile
	mkdir -p $(dir $@)
	mkdir -p $(dir $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d))
	$(CC) $(CFLAGS) -MMD -MP -MF $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d) -o $@ -c $<

$(OBJDIR)/%.o: $(SRCDIR)/%.asm Makefile
	mkdir -p $(dir $@)
	$(ASM) $(ASMFLAGS) -o $@ $<

$(OUTPUT_KERNEL): $(OBJECTS) $(ADDITIONAL_OBJECTS)
	$(LINK) -o $@ $(OBJECTS) $(LDFLAGS)

$(OUTPUT_PROGRAM): $(OBJECTS)
	$(LINK) -o $@ $(OBJECTS) $(LDFLAGS)

$(OUTPUT_STATIC_LIB): $(OBJECTS)
	$(AR) rcs $@ $^

$(OUTPUT_DYNAMIC_LIB) $(OUTPUT_DRIVER): $(OBJECTS)
	$(LINK) -shared -o $@ $(OBJECTS) $(LDFLAGS)
